package com.sun.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * 属性文件工具类
 * 
 * @author firefly
 *
 */
public class PropertiesUtil {
	private static final String APP_MESSAGES_PATH = "/config/app.properties";

	public static Map<String, String> listProperties() throws Exception {
		Map<String, String> map = new HashMap<>();
		InputStream in = null;
		try {
			File file = new File(PropertiesUtilTest.class.getResource("/").getPath() + APP_MESSAGES_PATH);
			in = new FileInputStream(file);
			Properties properties = new Properties();
			properties.load(in);
			for (Object key : properties.keySet()) {
				if (key == null) {
					continue;
				}
				map.put(key.toString(), properties.getProperty(key.toString()));
			}
			return map;
		} catch (IOException e) {
			e.printStackTrace();
			throw new Exception();
		} finally {
			if (null != in) {
				try {
					in.close();
				} catch (IOException e) {
				}
			}
		}
	}

	public static String getProperties(String key) throws Exception {
		InputStream in = null;
		try {
			File file = new File(PropertiesUtilTest.class.getResource("/").getPath() + APP_MESSAGES_PATH);
			in = new FileInputStream(file);
			Properties properties = new Properties();
			properties.load(in);
			return properties.getProperty(key);
		} catch (IOException e) {
			throw new Exception();
		} finally {
			if (null != in) {
				try {
					in.close();
				} catch (IOException e) {
				}
			}
		}
	}

	public static void setProperties(String key, String rebuldDb) throws Exception {
		InputStream in = null;
		try {
			File file = new File(PropertiesUtilTest.class.getResource("/").getPath() + APP_MESSAGES_PATH);
			in = new FileInputStream(file);
			Properties properties = new Properties();
			properties.load(in);
			properties.setProperty(key, rebuldDb);
			properties.store(new FileOutputStream(file), properties.toString());
		} catch (IOException e) {
			throw new Exception();
		} finally {
			if (null != in) {
				try {
					in.close();
				} catch (IOException e) {
				}
			}
		}
	}
}
